# Create your views here.
from django.shortcuts import get_object_or_404, render_to_response
from django.template import Context, loader,RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from myEvents.models import * 
from myEvents.forms  import IndexForm,AdminForm,VoteForm
from django.forms.fields import ChoiceField,MultipleChoiceField
from django.utils import simplejson

from django.core.mail import EmailMessage
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
import MySQLdb as mdb
import sys
import uuid

def enum(**enums):
    return type('Enum', (), enums)
def make_uuid():
    return str(uuid.uuid4().hex)

EVENT_STATUS = enum(INIT=0,VOTING=1,TERMINATED=2)
VOTE_STATUS = enum(NO=-1,YES=1,DONTKNOW=2)

def getNamebyEmail(email):
    parts = email.strip().split('@')
    return parts[0]
    
def attender(request,ehash,uhash):   
    try:
        e = Event.objects.get(ehash=ehash)
        u = User.objects.get(uhash=uhash)
        admin = Event_User.objects.get(event_id=e.id, role='admin')
        adminu = User.objects.get(id=admin.user_id)
        restaurants = getEventPlaces(ehash)
        init_pos_votes = {}
        init_neg_votes = {}
        for rest in restaurants:
            init_pos_votes[rest.id] = getPlaceVote(e.id,rest.id,1)
            init_neg_votes[rest.id] = getPlaceVote(e.id,rest.id,-1)
        data = {'places':restaurants,'posvotes':init_pos_votes,'negvotes':init_neg_votes,
                'myname':u.name,'adminname':adminu.name,'event':e,'ehash':ehash,'uhash':uhash}
        return render_to_response('myEvents/attender.html',data,context_instance=RequestContext(request))
    except Event.DoesNotExist, User.DoesNotExist:
        return render_to_response('myEvents/error.html',{'message':"event or user doesnt exist"},context_instance=RequestContext(request))

def vote(request,ehash,uhash):
    if request.method == "POST":    
        #if request.method == "POST" and form.is_valid():
        restaurants = getEventPlaces(ehash)
        form = VoteForm(restaurants,request.POST)
        #form = VoteForm(request.POST or None)
        #form_status = form.is_valid()
        form_status =True
        #if  form.is_valid():   #why this form is not valid? something wrong for the multiplechoice
        if form_status:
            place_names=[]
            #places = form.places
            places = request.POST.getlist('places')
            place_names = updatePoll(ehash,uhash,places)
            data = {'places':place_names}
            return render_to_response('myEvents/votesuccess.html',data,context_instance=RequestContext(request))
        else:
            form = VoteForm()
            return render_to_response('myEvents/error.html',{'adminForm':form},context_instance=RequestContext(request))
    
    return render_to_response('myEvents/attender.html',{'form':form},context_instance=RequestContext(request))

def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]
    
# get a list of place objects associated to this event
def getEventPlaces(ehash):
    restaurants=[]
    try:
        e = Event.objects.get(ehash=ehash)
    except Event.DoesnotExist:
        return restaurants
    #retrieve all distinct places for the event, return a list of dict{'place':plid, 'place':plid}
    places = Event_Place.objects.filter(event=e).distinct().values('place')
    
    for pl in places:
        rest = Place.objects.get(id=pl['place'])
        restaurants.append(rest)
    return restaurants

#DB operation
def updatePoll(ehash,uhash,places):
    place_names=[]
    for plid  in places:
        p = Place.objects.get(id=plid)
        place_names.append(p.name)
        e = Event.objects.get(ehash=ehash)
        u = User.objects.get(uhash=uhash)
        ep = Poll.objects.create(event=e,user=u,place=p,vote=VOTE_STATUS.YES)
    return place_names

#DB operation
def getPlaceVote(event_id,place_id,vote):
    cnt = Poll.objects.filter(event_id=event_id, place_id=place_id, vote=vote).count()
    return cnt
    
def getPosVote(request,ehash,uhash):
    if request.method == "GET":    
        message = {"cnt": ""}
        try:
            e = Event.objects.get(ehash=ehash) 
            rest_id = request.GET.get('rest_id', '')
            cnt = getPlaceVote(e.id,rest_id,1)
            message['cnt'] = str(cnt)
            json = simplejson.dumps(message)
            return  HttpResponse(json, mimetype='application/json')
        except Event.DoesNotExist:
            return render_to_response('myEvents/error.html',{"There is no such event"},context_instance=RequestContext(request))
    return render_to_response('myEvents/error.html',{"should be a http GET"},context_instance=RequestContext(request))

def getNegVote(request,ehash,uhash):
    if request.method == "GET":    
        message = {"cnt": ""}
        try:
            e = Event.objects.get(ehash=ehash) 
            rest_id = request.GET.get('rest_id', '')
            cnt = getPlaceVote(e.id,rest_id,-1)
            message['cnt'] = str(cnt)
            json = simplejson.dumps(message)
            return  HttpResponse(json, mimetype='application/json')
        except Event.DoesNotExist:
            return render_to_response('myEvents/error.html',{"There is no such event"},context_instance=RequestContext(request))
    return render_to_response('myEvents/error.html',{"should be a http GET"},context_instance=RequestContext(request))

# DB operation
def setPlaceVote(event_id,user_id, place_id,vote):
    try:
        ep = Poll.objects.get(event_id=event_id,user_id=user_id,place_id=place_id)
        ep.vote = vote
        ep.save()
    except Poll.DoesNotExist:
        ep = Poll.objects.create(event_id=event_id, user_id=user_id,place_id = place_id, vote=vote)

def setVote(request,ehash,uhash):
    if request.method == "POST":    
        try:
            e = Event.objects.get(ehash=ehash) 
            u = User.objects.get(uhash=uhash)
            place_id = request.POST.get('place_id', '')
            vote  = request.POST.get('vote','')
            setPlaceVote(e.id,u.id,place_id,vote)
            json = simplejson.dumps({"message":"Vote Success!"})
            return HttpResponse(json, mimetype='application/json')
        except Event.DoesNotExist or User.DoesNotExist:
            json = simplejson.dumps({"message":"Wrong Event or User !"})
            return HttpResponse(json, mimetype='application/json')
    else:
        return render_to_response('myEvents/error.html',{"message":"the request is not a post"},context_instance=RequestContext(request))  
    
def xhr_test(request,ehash,uhash):
    if request.is_ajax():
        message = "Hello AJAX"
    else:
        message = "Hello"
    return HttpResponse(message)

def getMyVotes(request,ehash,uhash):
#    if request.is_ajax():
    e = Event.objects.get(ehash = ehash)
    u = User.objects.get(uhash = uhash)
    
    posids = Poll.objects.filter(event_id=e.id,user_id=u.id,vote=1).values('place')
    negids = Poll.objects.filter(event_id=e.id,user_id=u.id,vote=-1).values('place')
    likes = []
    dislikes = [] 
    for pl in posids:
        p = Place.objects.get(id = pl['place'])
        likes.append(p.name)
    
    for pl in negids:
        p = Place.objects.get(id = pl['place'])
        dislikes.append(p.name)
        
    json = simplejson.dumps({"likes":likes,'dislikes':dislikes})   
    return HttpResponse(json, mimetype='application/json')

def getVoteStats(request,ehash,uhash):
#    if request.is_ajax():
    e = Event.objects.get(ehash = ehash)
    u = User.objects.get(uhash = uhash)
    id = request.GET.get('rest_id', '')

    posids = Poll.objects.filter(event_id=e.id,place_id =id,vote=1).values('user')
    negids = Poll.objects.filter(event_id=e.id,place_id=id,vote=-1).values('user')
    likes = []
    dislikes = [] 
    for pl in posids:
        p = User.objects.get(id = pl['user'])
        likes.append(p.name)
    
    for pl in negids:
        p = User.objects.get(id = pl['user'])
        dislikes.append(p.name)
        
    json = simplejson.dumps({"likes":likes,'dislikes':dislikes})   
    return HttpResponse(json, mimetype='application/json')

def getVoteDate(request,ehash,uhash):
    e = Event.objects.get(ehash=ehash)
    #need the format of datetime object, otherwise json can't serialize it
    json = simplejson.dumps({"date":e.voteDate.isoformat()})
    return HttpResponse(json,mimetype="application/json")

def currentResult(request,ehash,uhash):
    from django.db import connection
    cursor = connection.cursor()
    e = Event.objects.get(ehash=ehash)
    query = "SELECT name, count(*) as cnt FROM myEvents_poll,myEvents_place WHERE myEvents_place.id=myEvents_poll.place_id AND event_id = %s AND vote = 1 GROUP BY place_id order by cnt desc" %e.id
    cursor.execute(query)
    rs = dictfetchall(cursor)
    if rs:  #if it's not empty
        currPl = rs[0]['name']
        numlikes = rs[0]['cnt']

        try:
            p = Place.objects.get(name=currPl)
            numdislikes = Poll.objects.filter(event_id=e.id,place_id=p.id, vote=-1).count()
            json = simplejson.dumps({"place":currPl,'numlikes':numlikes,'numdislikes':numdislikes})   
        except Place.DoesNotExist,Poll.DoesNotExist:
            json = simplejson.dumps({"place":currPl,'numlikes':numlikes,'numdislikes':0})   
            
    else:  #if no body vote on likes
        query = "SELECT name, count(*) as cnt FROM myEvents_poll,myEvents_place WHERE myEvents_place.id=myEvents_poll.place_id AND event_id = %s AND vote = -1 GROUP BY place_id order by cnt desc" %eid
        cursor.execute(query)
        rs = dictfetchall(cursor)
        if rs:
            dislikePl =rs[0]['name']
            numdislikes = rs[0]['cnt']
            json = simplejson.dumps({"place":dislikePl,'numlikes':0,'numdislikes':numdislikes})   
        else:
            json = simplejson.dumps({"place":"",'numlikes':0,'numdislikes':0})
        
    return HttpResponse(json,mimetype="application/json")
 